import { toast, tansParams } from './common'
// 针对nvue页面的请求封装
const request = config => {
  return new Promise((resolve, reject) => {
    if (!uni.getStorageSync('baseURL')) {
      // uni.setStorageSync('baseURL', 'localhost:3000') // 本地
      // uni.setStorageSync('baseURL', '124.221.253.237:80') // 投资管理
      // uni.setStorageSync('baseURL', '124.221.253.237:88') // 记账管理
      uni.setStorageSync('baseURL', '124.221.253.237:99') // 任务管理
    }
    const baseURL = `http://${uni.getStorageSync('baseURL')}`
    // 添加token
    config.header = config.header || {}
    if (uni.getStorageSync('token')) {
      config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token')
    } else {
      if (config.url !== '/api/login' && config.url !== '/api/getNotice') {
        uni.reLaunch({
          url: '/pages/login/index'
        })
        return
      }
    }
    // get请求映射params参数
    if (config.params) {
      let url = config.url + '?' + tansParams(config.params)
      url = url.slice(0, -1)
      config.url = url
    }
    // 本地服务器
    let urls = ''
    if (uni.getStorageSync('baseURL') === 'localhost:3000') {
      urls = baseURL + config.url.replace('/api', '', 1)
      uni.setStorageSync('getUploadApp', `${baseURL}/getUploadApp`)
    } else {
      urls = baseURL + config.url
      uni.setStorageSync('getUploadApp', `${baseURL}/api/getUploadApp`)
    }
    uni.request({
      url: urls,
      data: config.data,
      method: config.method || 'get',
      header: config.header,
      dataType: 'json',
      sslVerify: false,
      timeout: 10000
    }).then(response => {
      const [error, res] = response
      if (error) {
        toast('后端接口连接异常')
        reject('后端接口连接异常')
        return
      }
      const code = res.data.code || 200
      const msg = res.data.message
      if (res.statusCode === 404) {
        toast('接口404访问资源不存在')
        return
      } else if (res.statusCode === 401) {
        toast('接口401认证失败，无法访问系统资源')
        return
      } else if (res.statusCode === 403) {
        toast('接口403当前操作没有权限')
        return
      }
      if (code !== 200) {
        toast(msg)
        reject(code)
      }
      resolve(res.data)
      return res.data
    })
      .catch(error => {
        const { message } = error
        toast(message)
        reject(error)
      })
  })
}

export default request
